using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Caching;
using CMN.Common;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Web.Caching;
namespace CMN.Cache
{
    /// <summary>
    /// Asp.Net JsonFile缓存
    /// </summary>
    public class JsonFileCache<T> : ICMNCache
    {
       

        /// <summary>
        /// 插入值
        /// </summary>
        /// <param name="file">file</param>
        /// <param name="o">值</param>
        public void Insert(string file, object o)
        {
            Insert(file, o, 3600);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="cacheItem"></param>
        /// <param name="reason"></param>
        public void OnRemove(string key, object cacheItem, System.Web.Caching.CacheItemRemovedReason reason)
        {

            Remove(key);

        }

        /// <summary>
        /// 插入缓存
        /// </summary>
        /// <param name="file">file</param>
        /// <param name="o">值</param>
        /// <param name="moveMinutes">移除的分钟数</param>
        /// <param name="noUsingMinutes">多长时间没访问释放的秒数</param>
        public void Insert(string file, object o, double moveSeconds)
        {
            Insert(file, o, moveSeconds, false);

        }

        /// <summary>
        /// 插入缓存
        /// </summary>
        /// <param name="file">file</param>
        /// <param name="o">值</param>
        /// <param name="moveMinutes">移除的分钟数</param>
        /// <param name="noUsingMinutes">多长时间没访问释放的秒数</param>
        public void Insert(string file, object o, double moveSeconds, bool isAutoDelete)
        {
            if (o == null)
            {
                return;
            }
            DateTime dtTemp;
            dtTemp = DateTime.Now.AddSeconds(moveSeconds);
            string returnJson = string.Empty;
            if (isAutoDelete)
                returnJson = string.Concat(dtTemp.ToString("yyyy-MM-dd HH:mm:ss"), "I", JsonConvert.SerializeObject(o, Formatting.Indented));
            else
                returnJson = string.Concat(dtTemp.ToString("yyyy-MM-dd HH:mm:ss"), JsonConvert.SerializeObject(o, Formatting.Indented));

            if (!Directory.Exists(Path.GetDirectoryName(file)))
                Directory.CreateDirectory(Path.GetDirectoryName(file));
            try
            {
                if (File.Exists(file))
                {
                    using (FileStream fs = new FileStream(file, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        Byte[] info = System.Text.Encoding.UTF8.GetBytes(returnJson);
                        fs.Write(info, 0, info.Length);
                        fs.Flush();
                        fs.Close();
                        info = null;
                    }
                }
                else
                {
                    using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        Byte[] info = System.Text.Encoding.UTF8.GetBytes(returnJson);
                        fs.Write(info, 0, info.Length);
                        fs.Flush();
                        fs.Close();
                        info = null;
                    }
                }
                returnJson = null;
                if (isAutoDelete)
                {
                    System.Web.Caching.CacheItemRemovedCallback callback = new System.Web.Caching.CacheItemRemovedCallback(OnRemove);
                    HttpWebCache webCache = new HttpWebCache();
                    webCache.Insert(file, "", moveSeconds, CacheItemPriority.High, callback);
                }

            }
            catch (Exception ex)
            {
                AppLog.Write(string.Concat("jsonFile写入缓存", file, ex.Message), AppLog.LogMessageType.Error, ex);
            }


        }



        /// <summary>
        /// 移除值
        /// </summary>
        /// <param name="file">file</param>
        public void Remove(string file)
        {
            if (System.IO.File.Exists(file))
            {
                try
                {
                    
                        using (FileStream fs = new FileStream(file, FileMode.Truncate, FileAccess.Write, FileShare.Delete))
                        {
                            File.Delete(file);
                            fs.Close();
                            fs.Dispose();
                        }

                    
                    // AppLog.Write(string.Concat("jsonFile删除缓存", file), AppLog.LogMessageType.Info);
                }
                catch (Exception ex)
                {
                    AppLog.Write(string.Concat("jsonFile删除缓存", file, ex.Message), AppLog.LogMessageType.Error, ex);
                }
            }
        }
        public bool IsOutTime(string file)
        {
            string strFile = string.Empty;
            try
            {

                if (System.IO.File.Exists(file))
                {
                    using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                        {
                            strFile = sr.ReadToEnd();
                            sr.Close();
                            sr.Dispose();
                        }
                        fs.Close();
                        fs.Dispose();
                    }
                }
                else
                {
                    return true;
                }

                if (strFile.Length > 20)
                {
                    string stdt = strFile.Substring(0, 19);

                    DateTime dt = Utils.StringToDataTime(stdt);
                    stdt = "";
                    stdt = strFile.Substring(19, 1);

                    if (DateTime.Now >= dt)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                AppLog.Write(string.Concat("jsonFile读取缓存IsOutTime+", file, strFile, ex.Message), AppLog.LogMessageType.Error, ex);
            }
            return true;

        }

        /// <summary>
        /// 获得值
        /// </summary>
        /// <param name="file">键值</param>
        /// <returns>返回值</returns>
        public object this[string file]
        {
            get
            {
                string strFile = string.Empty;
                try
                {
                   
                    if (System.IO.File.Exists(file))
                    {
                        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                            {
                                strFile = sr.ReadToEnd();
                                sr.Close();
                                sr.Dispose();
                            }
                            fs.Close();
                            fs.Dispose();
                        }
                    }
                    //else
                    //{
                    //    return null;
                    //}
                    bool isAutoDelete=false;
                    if (strFile.Length > 20)
                    {
                        string stdt = strFile.Substring(0, 19);

                        DateTime dt = Utils.StringToDataTime(stdt);
                        stdt = "";
                        stdt = strFile.Substring(19, 1);
                        if (stdt == "I")
                            isAutoDelete = true;
                        else
                            isAutoDelete = false;
                        //if (DateTime.Now >= dt)
                        //{
                        //    //if (isAutoDelete)
                        //    //{
                        //    //    using (FileStream fs = new FileStream(file, FileMode.Truncate, FileAccess.Write, FileShare.Delete))
                        //    //    {
                        //    //        File.Delete(file);
                        //    //        fs.Close();
                        //    //        fs.Dispose();
                        //    //    }

                        //    //}
                        //    //else
                        //    //{
                        //    //    using (FileStream fs = new FileStream(file, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite))
                        //    //    {
                        //    //        fs.Close();
                        //    //        fs.Dispose();
                        //    //    }
                        //    //}
                        //    //return null;
                        //}
                        if (isAutoDelete)
                            strFile = strFile.Substring(20, (strFile.Length - 20));
                        else
                            strFile = strFile.Substring(19, (strFile.Length - 19));
                        //AppLog.Write(strFile, AppLog.LogMessageType.Debug);
                        if (strFile.StartsWith("["))
                        {
                            List<T> lt = (List<T>)JsonConvert.DeserializeObject(strFile, typeof(List<T>), new JsonSerializerSettings());
                            strFile = null;
                            return lt;
                        }
                        else
                        {
                            T t = (T)JsonConvert.DeserializeObject(strFile, typeof(T), new JsonSerializerSettings());
                            strFile = null;
                            return t;
                        }
                    }
                    else
                        return null;
                }
                catch (Exception ex)
                {
                    AppLog.Write(string.Concat("jsonFile读取缓存+", file,strFile, ex.Message), AppLog.LogMessageType.Error, ex);
                }
                return null;

            }
        }

        /// <summary>
        /// 获得使用缓存总数
        /// </summary>
        public int Count
        {
            get
            {
                return 0;
            }
        }

        /// <summary>
        /// 获得剩余缓存大小
        /// </summary>
        public string Remains
        {
            get
            {
                return string.Format("{0}M");
            }
        }
    }
}